<?php

namespace app\shop\model\menu;

use app\common\model\menu\Menu as MenuModel;
use think\facade\Cache;

/**
 * 广告分类模型
 */
class Menu extends MenuModel
{
    /**
     * 添加新记录
     */
    public function add($data)
    {
        //查询上级
        if ($data['parent_id'] > 0) {
            $parentInfo = $this->where('menu_id', '=', $data['parent_id'])->find();
            $data['level'] = $parentInfo['level'] + 1;
            $data['topid'] = !empty($parentInfo['topid']) ? $parentInfo['topid'] : $parentInfo['menu_id'];
        }
        $data['app_id'] = self::$app_id;
        $this->deleteCache();
        return $this->save($data);
    }

    /**
     * 编辑记录
     */
    public function edit($data)
    {
        if ($data['parent_id'] > 0) {
            $parentInfo = $this->where('menu_id', '=', $data['parent_id'])->find();
            $data['level'] = $parentInfo['level'] + 1;
            $data['topid'] = !empty($parentInfo['topid']) ? $parentInfo['topid'] : $parentInfo['menu_id'];
        }
        $this->deleteCache();
        return $this->save($data);
    }

    /**
     * 编辑记录
     */
    public function setStatus($data)
    {
        $this->deleteCache();
        return $this->save($data) !== false;
    }

    /**
     * 删除分类
     */
    public function remove()
    {
        $this->deleteCache();
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 删除缓存
     */
    private function deleteCache()
    {
        return Cache::delete('menu_' . static::$app_id);
    }

    /**
     * 获取添加内容栏目
     */
    public function getList()
    {
        $arr = $this->with('mould')
            ->where('mould_id', '<>', 5)
            ->where('is_delete', '=', 0)
            ->order(['sort' => 'asc', 'create_time' => 'asc'])
            ->select()->toArray();
        $list = $this->getTree($arr, $pid = 0, $level = 0);
        return $list;
    }

}